#include "board.h"
#include <QMessageBox>
#include "info_dialog.h"
#include "cabinet_dialog.h"
#include "admin_dialog.h"

void Board::handleAdmin(QWidget *window)
{
    AdminDialog dlg(window);
    if (dlg.exec() == QDialog::Accepted)
    {
        InfoDialog infoDialog(window);
        infoDialog.setWindowTitle("信息录入");
        infoDialog.exec();
    }
}

void Board::handleStore(QWidget *window)
{
    if (!loadDeviceConfig())
    {
        showBigMessageBox(window, QMessageBox::Warning, "配置错误", "未找到设备配置信息，请先点击「管理员登录」进行设备配置!");
        return;
    }

    CabinetCollectDialog dlg(window);

    // 柜层下拉框选项变化时，更新柜子数量
    QObject::connect(dlg.layerCombo, &QComboBox::currentTextChanged,
        [&](const QString &layer){
            int amount = httpGetAmountCabinetByLayer(
                deviceConfig.brand_code.toStdString(),
                deviceConfig.organization.toStdString(),
                deviceConfig.zone.toStdString(),
                layer.toStdString()
            );
            dlg.layerNumberLabel->setText(QString("该层柜子可用数量：%1").arg(amount));
        });
    
    // 初始化时也设置一次
    {
        QString layer = dlg.layerCombo->currentText();
        int amount = httpGetAmountCabinetByLayer(
            deviceConfig.brand_code.toStdString(),
            deviceConfig.organization.toStdString(),
            deviceConfig.zone.toStdString(),
            layer.toStdString()
        );
        dlg.layerNumberLabel->setText(QString("该层柜子可用数量：%1").arg(amount));
    }
    QObject::connect(&dlg, &CabinetCollectDialog::phonePasswordCollectRequested,
                     [&](const QString &phone, const QString &pwd, const QString &layer)
                     {
                         // 原有业务逻辑
                         if (phone.isEmpty() || pwd.isEmpty())
                         {
                             showBigMessageBox(window, QMessageBox::Warning, "输入错误", "请输入电话号码和密码!");
                             return;
                         }
                         std::string serverPassword = httpGetPersonPasswd(
                             deviceConfig.brand_code.toStdString(),
                             deviceConfig.organization.toStdString(),
                             deviceConfig.zone.toStdString(),
                             phone.toStdString());
                         if (serverPassword.empty() || pwd.toStdString() != serverPassword)
                         {
                             showBigMessageBox(window, QMessageBox::Warning, "验证失败", "会员信息或密码错误!");
                             return;
                         }
                         Lock lock = httpDistributeLock(
                             deviceConfig.brand_code.toStdString(),
                             deviceConfig.organization.toStdString(),
                             deviceConfig.zone.toStdString(),
                             phone.toStdString(), "流动柜", layer.toStdString());
                         if (lock.controller_id.empty() || lock.lock_numble.empty())
                         {
                             showBigMessageBox(window, QMessageBox::Warning, "分配失败", "无法分配柜子，请联系工作人员!");
                             return;
                         }
                        int controller_id = 0, lock_number = 0, cabinet_number = 0;
                        try {
                            controller_id = std::stoi(lock.controller_id);
                            lock_number = std::stoi(lock.lock_numble);
                            cabinet_number = std::stoi(lock.cabinet_number);
                        } catch (const std::exception &e) {
                            showBigMessageBox(window, QMessageBox::Warning, "数据错误", "柜子信息格式错误，请联系工作人员!");
                            return;
                        }
                         bool openResult = serial_->openLock(controller_id, lock_number);
                         if (openResult)
                         {
                             showBigMessageBox(window, QMessageBox::Information, "存包成功",  QString("已为您分配 %1 号柜子\n请记住您的电话号码和密码，取物时需使用").arg(cabinet_number));
                             httpUploadLog(
                                 deviceConfig.brand_code.toStdString(),
                                 deviceConfig.organization.toStdString(),
                                 deviceConfig.zone.toStdString(),
                                 phone.toStdString(),
                                 std::to_string(cabinet_number),
                                 "流动柜",
                                 "领柜存包"
                             );
                             dlg.accept(); // 关闭弹窗，返回上一个页面
                            }
                         else
                         {
                             showBigMessageBox(window, QMessageBox::Information, "开锁失败",  "柜子已分配，但开锁失败，请联系工作人员");
                         }
                     });

    QObject::connect(&dlg, &CabinetCollectDialog::braceletPalmCollectRequested,
                     [&]()
                     {
                         // 这里处理手环/掌静脉领柜的业务
                         // 可按你的原有逻辑填写
                     });

    dlg.exec();
}

void Board::handleHalfway(QWidget *window)
{
    if (!loadDeviceConfig())
    {
        showBigMessageBox(window, QMessageBox::Warning, "配置错误", "未找到设备配置信息，请先点击「管理员登录」进行设备配置!");
        return;
    }

    CabinetHalfwayDialog dlg(window);

    QObject::connect(&dlg, &CabinetHalfwayDialog::phonePasswordHalfwayRequested,
                     [&](const QString &phone, const QString &pwd)
                     {
                         // 原有业务逻辑
                         if (phone.isEmpty() || pwd.isEmpty())
                         {
                             showBigMessageBox(window, QMessageBox::Warning, "输入错误", "请输入电话号码和密码!");
                             return;
                         }
                         std::string serverPassword = httpGetPersonPasswd(
                             deviceConfig.brand_code.toStdString(),
                             deviceConfig.organization.toStdString(),
                             deviceConfig.zone.toStdString(),
                             phone.toStdString());
                         if (serverPassword.empty() || pwd.toStdString() != serverPassword)
                         {
                             showBigMessageBox(window, QMessageBox::Warning, "验证失败","会员信息或密码错误!");
                             return;
                         }
                         Lock lock = httpQueryLock(
                             deviceConfig.brand_code.toStdString(),
                             deviceConfig.organization.toStdString(),
                             deviceConfig.zone.toStdString(),
                             phone.toStdString(), "流动柜");
                         if (lock.controller_id.empty() || lock.lock_numble.empty())
                         {
                             showBigMessageBox(window, QMessageBox::Warning, "查询失败","未找到您分配的柜子，请确认是否已存包!");
                             return;
                         }
                        int controller_id = 0, lock_number = 0, cabinet_number = 0;
                        try {
                            controller_id = std::stoi(lock.controller_id);
                            lock_number = std::stoi(lock.lock_numble);
                            cabinet_number = std::stoi(lock.cabinet_number);
                        } catch (const std::exception &e) {
                            showBigMessageBox(window, QMessageBox::Warning, "数据错误","柜子信息格式错误，请联系工作人员!");
                            return;
                        }
                         bool openResult = serial_->openLock(controller_id, lock_number);
                         if (openResult)
                         {
                             showBigMessageBox(window, QMessageBox::Information, "开柜成功",QString("已为您打开 %1 号柜子\n请取出物品，记得关闭柜门").arg(cabinet_number));
                             httpUploadLog(
                                 deviceConfig.brand_code.toStdString(),
                                 deviceConfig.organization.toStdString(),
                                 deviceConfig.zone.toStdString(),
                                 phone.toStdString(),
                                 std::to_string(cabinet_number),
                                 "流动柜",
                                 "中途取物"
                             );
                             dlg.accept(); // 关闭弹窗，返回上一个页面
                            }
                         else
                         {
                            showBigMessageBox(window, QMessageBox::Warning, "数据错误","柜子信息格式错误，请联系工作人员!");
                         }
                     });

    QObject::connect(&dlg, &CabinetHalfwayDialog::braceletPalmHalfwayRequested,
                     [&]()
                     {
                         // 这里处理手环/掌静脉开柜的业务
                         // 可按你的原有逻辑填写
                     });

    dlg.exec();
}

void Board::handleReturn(QWidget *window)
{
    if (!loadDeviceConfig())
    {
        showBigMessageBox(window, QMessageBox::Warning, "配置错误","未找到设备配置信息，请先点击「管理员登录」进行设备配置!");
        return;
    }

    CabinetHalfwayDialog dlg(window);

    QObject::connect(&dlg, &CabinetHalfwayDialog::phonePasswordHalfwayRequested,
                     [&](const QString &phone, const QString &pwd)
                     {
                         // 原有业务逻辑
                         if (phone.isEmpty() || pwd.isEmpty())
                         {
                             showBigMessageBox(window, QMessageBox::Warning, "输入错误","请输入电话号码和密码!");
                             return;
                         }
                         std::string serverPassword = httpGetPersonPasswd(
                             deviceConfig.brand_code.toStdString(),
                             deviceConfig.organization.toStdString(),
                             deviceConfig.zone.toStdString(),
                             phone.toStdString());
                         if (serverPassword.empty() || pwd.toStdString() != serverPassword)
                         {
                             showBigMessageBox(window, QMessageBox::Warning, "验证失败","会员信息或密码错误!");
                             return;
                         }
                         Lock lock = httpQueryLock(
                             deviceConfig.brand_code.toStdString(),
                             deviceConfig.organization.toStdString(),
                             deviceConfig.zone.toStdString(),
                             phone.toStdString(), "流动柜");
                         if (lock.controller_id.empty() || lock.lock_numble.empty())
                         {
                             showBigMessageBox(window, QMessageBox::Warning, "查询失败","未找到您分配的柜子，请确认是否已存包!");
                             return;
                         }
                         int controller_id = 0, lock_number = 0, cabinet_number = 0;
                         try {
                             controller_id = std::stoi(lock.controller_id);
                             lock_number = std::stoi(lock.lock_numble);
                             cabinet_number = std::stoi(lock.cabinet_number);
                         } catch (const std::exception &e) {
                             showBigMessageBox(window, QMessageBox::Warning, "数据错误","柜子信息格式错误，请联系工作人员!");
                             return;
                         }
                         httpReturnLock(
                             deviceConfig.brand_code.toStdString(),
                             deviceConfig.organization.toStdString(),
                             deviceConfig.zone.toStdString(),
                             phone.toStdString(), "流动柜");
                         // 忽略归还结果，直接尝试开锁
                         bool openResult = serial_->openLock(controller_id, lock_number);
                         if (openResult)
                         {
                             showBigMessageBox(window, QMessageBox::Information, "退柜成功",QString("已为您打开 %1 号柜子\n请取出物品，记得关闭柜门").arg(cabinet_number));
                             httpUploadLog(
                                 deviceConfig.brand_code.toStdString(),
                                 deviceConfig.organization.toStdString(),
                                 deviceConfig.zone.toStdString(),
                                 phone.toStdString(),
                                 std::to_string(cabinet_number),
                                 "流动柜",
                                 "退柜取物"
                             );
                             dlg.accept(); // 关闭弹窗，返回上一个页面
                            }
                         else
                         {
                             showBigMessageBox(window, QMessageBox::Warning, "开锁失败","开锁失败，请联系工作人员");
                         }
                     });

    QObject::connect(&dlg, &CabinetHalfwayDialog::braceletPalmHalfwayRequested,
                     [&]()
                     {
                         // 这里处理手环/掌静脉开柜的业务
                         // 可按你的原有逻辑填写
                     });

    dlg.exec();
}



void Board::handleLongRent(QWidget *window)
{
        if (!loadDeviceConfig())
    {
        showBigMessageBox(window, QMessageBox::Warning, "配置错误","未找到设备配置信息，请先点击「管理员登录」进行设备配置!");
        return;
    }

    CabinetHalfwayDialog dlg(window);

    QObject::connect(&dlg, &CabinetHalfwayDialog::phonePasswordHalfwayRequested,
                     [&](const QString &phone, const QString &pwd)
                     {
                         // 原有业务逻辑
                         if (phone.isEmpty() || pwd.isEmpty())
                         {
                             showBigMessageBox(window, QMessageBox::Warning, "输入错误","请输入电话号码和密码!");
                             return;
                         }
                         std::string serverPassword = httpGetPersonPasswd(
                             deviceConfig.brand_code.toStdString(),
                             deviceConfig.organization.toStdString(),
                             deviceConfig.zone.toStdString(),
                             phone.toStdString());
                         if (serverPassword.empty() || pwd.toStdString() != serverPassword)
                         {
                             showBigMessageBox(window, QMessageBox::Warning, "验证失败","会员信息或密码错误!");
                             return;
                         }
                         Lock lock = httpQueryLock(
                             deviceConfig.brand_code.toStdString(),
                             deviceConfig.organization.toStdString(),
                             deviceConfig.zone.toStdString(),
                             phone.toStdString(), "长租柜");
                         if (lock.controller_id.empty() || lock.lock_numble.empty())
                         {
                             showBigMessageBox(window, QMessageBox::Warning, "查询失败","未找到您分配的柜子，请确认是否已存包!");
                             return;
                         }
                        int controller_id = 0, lock_number = 0, cabinet_number = 0;
                        try {
                            controller_id = std::stoi(lock.controller_id);
                            lock_number = std::stoi(lock.lock_numble);
                            cabinet_number = std::stoi(lock.cabinet_number);
                        } catch (const std::exception &e) {
                            showBigMessageBox(window, QMessageBox::Warning, "数据错误","柜子信息格式错误，请联系工作人员!");
                            return;
                        }
                         bool openResult = serial_->openLock(controller_id, lock_number);
                         if (openResult)
                         {
                             showBigMessageBox(window, QMessageBox::Information, "开柜成功",QString("已为您打开 %1 号柜子\n请取出物品，记得关闭柜门").arg(cabinet_number));
                             httpUploadLog(
                                 deviceConfig.brand_code.toStdString(),
                                 deviceConfig.organization.toStdString(),
                                 deviceConfig.zone.toStdString(),
                                 phone.toStdString(),
                                 std::to_string(cabinet_number),
                                 "长租柜",
                                 "中途取物"
                             );
                             dlg.accept(); // 关闭弹窗，返回上一个页面
                            }
                         else
                         {
                            showBigMessageBox(window, QMessageBox::Warning, "开锁失败","开锁失败，请联系工作人员");
                         }
                     });

    QObject::connect(&dlg, &CabinetHalfwayDialog::braceletPalmHalfwayRequested,
                     [&]()
                     {
                         // 这里处理手环/掌静脉开柜的业务
                         // 可按你的原有逻辑填写
                     });

    dlg.exec();
}